import 'dart:collection';

import 'package:flutter/material.dart';

/// @author dayo
/// @created at 2024/1/3 20:19
/// @desc: 富文本, 仅支持自定义高亮, 类似iOS属性text
///
class GTHighlighterTextEntry {
  final String text;
  final TextStyle style;
  GTHighlighterTextEntry({
    required this.text,
    required this.style,
  });
}

class GTHighlighterText extends StatelessWidget {
  final String text; //全量字符串
  final TextStyle style; //通用的字体样式

  final List<GTHighlighterTextEntry> textEntries;//需要高亮的字体文本 和 字体样式
  const GTHighlighterText(
    this.text, {
    super.key,
    required this.style,
    required this.textEntries,
  });

  @override
  Widget build(BuildContext context) {
    // RichText
    return Text.rich(TextSpan(children: _initWidget()));
  }

  List<TextSpan> _initWidget() {
    String tmpText = text;
    //移除不匹配元素
    List<GTHighlighterTextEntry> filterEntries = textEntries.where((e) => tmpText.contains(e.text)).toList();

    //创建有序字典
    SplayTreeMap<int, GTHighlighterTextEntry> entriesWithIndex = SplayTreeMap<int, GTHighlighterTextEntry>();
    for (var entry in filterEntries) {
      int i = 0;
      while (entry.text.isNotEmpty == true && i >= 0 && tmpText.indexOf(entry.text, i) >= 0) {
        entriesWithIndex[tmpText.indexOf(entry.text, i)] = entry;
        i = i + entry.text.length;
      }
    }

    List<TextSpan> textSpans = [];
    entriesWithIndex.forEach((key, value) {
      if (tmpText.indexOf(value.text) > 0) {
        String normalText = tmpText.substring(0, tmpText.indexOf(value.text));
        textSpans.add(TextSpan(
          text: normalText,
          style: style,
        ));
      }
      textSpans.add(TextSpan(
        text: value.text,
        style: value.style,
      ));

      tmpText = tmpText.replaceRange(0, tmpText.indexOf(value.text) + value.text.length, '');
    });
    if (tmpText.isNotEmpty) {
      textSpans.add(TextSpan(
        text: tmpText,
        style: style,
      ));
    }

    return textSpans;
  }
}
